package com.example.gamestore.service.imp;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.gamestore.Bean.Admin;
import com.example.gamestore.Utils.JWTUtils;
import com.example.gamestore.mapper.AdminMapper;
import com.example.gamestore.service.AdminService;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdminServiceImp implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Admin login(Admin admin) {
        String username = admin.getUsername();
        String password = admin.getPassword();
        LambdaQueryWrapper<Admin> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getUsername,username).eq(Admin::getPassword,password);
        Admin admin1 = adminMapper.selectOne(wrapper);
        if(admin1!=null){
            String token = JWTUtils.createToken(admin1.getId());
            redisTemplate.opsForValue().set("token_"+token,JSON.toJSONString(admin1),1, TimeUnit.DAYS);
//            String json=JSON.toJSONString(admin1);
//            String userJson = (String) redisTemplate.opsForValue().get("token_" + token);
//            System.out.println(json);
//            System.out.println(userJson);
//            Admin adminss = JSON.parseObject(userJson, Admin.class);
//            System.out.println(adminss);
            return admin1;
        }
        return null;
    }

    @Override
    public Admin checktoken(String token) {
        if(StringUtils.isNullOrEmpty(token)){
            return null;
        }
        Map<String, Object> map = JWTUtils.checkToken(token);
        if(map==null){
            return null;
        }
        String userJson = (String) redisTemplate.opsForValue().get("token_" + token);
        if(StringUtils.isNullOrEmpty(userJson)){
            return null;
        }
        Admin admin = JSON.parseObject(userJson, Admin.class);
        System.out.println(admin);
        return admin;
    }
}
